/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\StatementOfAccount\SendStatementOfAccount\index.tsx
 * @Date: 2022-03-14 13:56:47
 * @LastEditTime: 2022-05-17 11:02:24
 */
import { http, UdDatePicker, UdDrawer, UdForm, UdModal, UdPage, UdPageHeader, validators } from '@/lib'
import React from 'react'
import udMainStore from '@/store/UdMain'
import UdSelect from '@/components/UdFormControls/UdSelect'
import SelectView from './components/SelectView'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import { useMount, useSafeState, useUpdateEffect } from 'ahooks'
import TextAreaView from './components/TextAreaView'
import SelectDistributor from './components/SelectDistributor'
import StatementOfAccountInfo from './components/StatementOfAccountInfo2'
import { Input, message } from 'antd'
import apis from '@/apis/StatementOfAccount/index'
import './style.scss'
import { unionBy } from 'lodash'

const labelCol: object = { span: 2 }

const SendStatementOfAccount = props => {
  const brandList: any[] = udMainStore.brandList
  const [form, setform] = useSafeState<WrappedFormUtils>(null)
  const [templateList, setTemplateList] = useSafeState<any[]>([])
  const [templateOptions, setTemplateOptions] = useSafeState<any[]>([])
  const [distributorList, setDistributorList] = useSafeState<Record<string, any>[]>([])
  const [brandCode, setBrandCode] = useSafeState<string>(brandList[0].value)
  useMount(() => {
    getAllReconciliation()
  })

  useUpdateEffect(() => {
    const options = templateList?.map(({ id: value, modelName: title }) => ({ value, title })) || []
    setTemplateOptions(options)
  }, [templateList])

  useUpdateEffect(() => {
    form.setFieldsValue(
      { letterName: undefined, launchTime: undefined, templateModelId: undefined, distributor: undefined },
      () => {
        getAllReconciliation()
        setDistributorList([])
      }
    )
  }, [brandCode])

  useUpdateEffect(() => {
    form.setFieldsValue({ distributor: distributorList.map(({ agentName }) => agentName).join('、') })
  }, [distributorList])

  const getAllReconciliation = () => {
    setTemplateList([])
    http.get(apis.getAllReconciliation, { params: { brandCode } }).then(res => {
      let { data = [] } = res
      setTemplateList([...data])
    })
  }

  const handSubmit = (values): void => {
    UdDrawer.open({
      title: '经销商对账函信息',
      width: '60%',
      content: <StatementOfAccountInfo distributorList={distributorList} values={values} history={props.history} />,
    })
  }

  const handTemplateView = (): void => {
    const templateValue = form.getFieldValue('templateModelId')
    if (templateValue) {
      const rex = /^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?/
      const modelObj: { modelUrl; modelName } = templateList.find(item => {
        return item.id === templateValue
      })
      const { modelUrl, modelName } = modelObj
      if (rex.test(modelUrl)) {
        UdModal.open({
          title: modelName,
          width: '80%',
          bodyStyle: { padding: '0' },
          content: (
            <div style={{ height: '700px', overflow: 'hidden' }}>
              <iframe
                title={modelName}
                src={`https://view.officeapps.live.com/op/view.aspx?src=${modelUrl}`}
                width="100%"
                height="100%"
                frameBorder="0"
                style={{ border: 'none' }}
                seamless
              ></iframe>
            </div>
          ),
          footer: null,
        })
      } else {
        message.error('附件URL无效')
      }
    }
  }

  const handSelectDealer = (): void => {
    let brandName = brandList.find(item => {
      return item.value === brandCode
    })?.title
    UdDrawer.open({
      title: `选择经销商-${brandName}`,
      width: '60%',
      content: (
        <SelectDistributor
          brandCode={brandCode}
          dataSource={distributorList}
          onGetDataSource={params => {
            onGetDataSource(params)
          }}
        />
      ),
    })
  }

  const onGetDataSource = (params: Record<string, any>[]): void => {
    // setDistributorList(unionBy(distributorList, params, 'id'))
    setDistributorList(params)
  }

  return (
    <UdPage className="list-page">
      <UdPageHeader title="发起对账函" />
      <UdForm
        getForm={form => {
          setform(form)
        }}
        labelCol={labelCol}
        items={[
          {
            id: 'brandCode',
            label: '品牌公司',
            rules: [validators.required],
            initialValue: brandCode,
            render: () => (
              <UdSelect
                showSearch
                allowClear={false}
                options={brandList}
                onChange={value => {
                  setBrandCode(value)
                }}
              />
            ),
          },
          {
            id: 'letterName',
            label: '对账函名称',
            rules: [validators.required],
            render: () => <Input maxLength={15} autoComplete="off" />,
          },
          {
            id: 'launchTime',
            label: '截至日期',
            rules: [validators.required],
            render: () => <UdDatePicker style={{ width: '100%' }} />,
          },
          {
            id: 'templateModelId',
            label: '对账函模板',
            rules: [validators.required],
            render: () => <SelectView options={templateOptions} buttonClick={handTemplateView} />,
          },
          {
            id: 'distributor',
            label: '经销商',
            rules: [validators.required],
            render: <TextAreaView buttonClick={handSelectDealer} readOnly={true} placeholder="请选择经销商" />,
          },
        ]}
        onSubmit={handSubmit}
        footer="提交"
      />
    </UdPage>
  )
}

export default React.memo(SendStatementOfAccount)
